package com.example.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.Lawyer;
import com.example.service.LawyerService;
import com.example.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;
import com.example.exception.CustomException;
import cn.hutool.core.util.StrUtil;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/lawyer")
public class LawyerController {
    @Resource
    private LawyerService lawyerService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;

    public User getUser() {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            throw new CustomException("-1", "请登录");
        }
        return user;
    }

    @PostMapping
    public Result<?> save(@RequestBody Lawyer lawyer) {
        String uuid = UUID.randomUUID().toString();
        lawyer.setUuid(uuid);
        boolean save = lawyerService.save(lawyer);
        //律师需要在用户表注册
        User user = new User();
        user.setUsername(lawyer.getName());
        user.setLawyerUuid(uuid);
        user.setPhone(lawyer.getContactNumber());
        user.setPassword("123456");
        user.setIdentify("律师");
        //注册
        userService.register(user);
        return Result.success(save);
    }

    @PutMapping
    public Result<?> update(@RequestBody Lawyer lawyer) {
        return Result.success(lawyerService.updateById(lawyer));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        lawyerService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(lawyerService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        return Result.success(lawyerService.list());
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Lawyer> query = Wrappers.<Lawyer>lambdaQuery().orderByDesc(Lawyer::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(Lawyer::getName, name);
        }
        return Result.success(lawyerService.page(new Page<>(pageNum, pageSize), query));
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<Lawyer> all = lawyerService.list();
        for (Lawyer obj : all) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("id", obj.getId());
            row.put("律师姓名", obj.getName());
            row.put("性别", obj.getGender());
            row.put("出生日期", obj.getBirth());
            row.put("电话号码", obj.getContactNumber());
            row.put("邮箱", obj.getEmail());
            row.put("地址", obj.getAddress());
            row.put("专长领域", obj.getExpertise());
            row.put("执业资格证书编号", obj.getLicenseNumber());
            row.put("执业资格证书颁发机构", obj.getLicenseIssuingAuthority());
            row.put("执业资格证书颁发日期", obj.getLicenseIssueDate());
            row.put("是否审核通过", obj.getIsApproved());
            row.put("创建日期", obj.getCreateTime());
            row.put("更新时间", obj.getUpdateTime());

            list.add(row);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("律师管理信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

    @GetMapping("/upload/{fileId}")
    public Result<?> upload(@PathVariable String fileId) {
        String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String file = fileNames.stream().filter(name -> name.contains(fileId)).findAny().orElse("");
        List<List<Object>> lists = ExcelUtil.getReader(basePath + file).read(1);
        List<Lawyer> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            Lawyer obj = new Lawyer();
            obj.setName((String) row.get(1));
            obj.setGender((String) row.get(2));
            obj.setBirth(DateUtil.parseDateTime((String) row.get(3)));
            obj.setContactNumber((String) row.get(4));
            obj.setEmail((String) row.get(5));
            obj.setAddress((String) row.get(6));
            obj.setExpertise((String) row.get(7));
            obj.setLicenseNumber((String) row.get(8));
            obj.setLicenseIssuingAuthority((String) row.get(9));
            obj.setLicenseIssueDate(DateUtil.parseDateTime((String) row.get(10)));
            obj.setIsApproved((String) row.get(11));
            obj.setCreateTime(DateUtil.parseDateTime((String) row.get(12)));
            obj.setUpdateTime(DateUtil.parseDateTime((String) row.get(13)));

            saveList.add(obj);
        }
        lawyerService.saveBatch(saveList);
        return Result.success();
    }

}
